<?php
/**
 +------------------------------------------------------------------------------
 * Biz云购用户信息操作
 +------------------------------------------------------------------------------
 * @package  app
 * @author   alpha <QQ:411083658>
 * @date 2013-9-12
 * @time  下午13:38:07
 +------------------------------------------------------------------------------
 */
class Biz {
	protected $dao,$daolog,$post;
	protected $userid=0;
	protected $debug=array();
	protected $isdebug = 0,$isecho = 0;
	protected $platform = 'SMW01';
	/**
	 * 实例化云购用户信息类函数
	 * */
	function __construct(){
		$this->dao = M('UserBiz');
		$this->daolog = M('UserBizLog');
	}
	/**
	 * 云购用户列表
	 * @param array     $_arr=array(
	 * 					'user_id'=>用户ID,
	 * 					'contract_sn'=>合同编号,
	 * 					'stype'=>分销角色类型,
	 * 					'pay_status'=>付款状态,
	 * 					'status'=>申核状态,
	 * 					'isclose'=>开通状态,
	 * 					'province' => 省份ID，
	 * 					'city' => 城市ID，
	 * 					'area' => 区域ID
	 * 					)
	 * @return array
	 * */
	 function biz_list($_arr=array(),$limit = '0,20',$order = 'id DESC'){
	 	$this->dao = M('UserBiz');
	 	// 云购用户列表相关查询
	 	$model = $this->dao;
		$where = array();
		if($_arr != 'all'){
			foreach ($_arr as $key => $value) {
				$where[$key] = $value;
			}
		}
		if (strtolower ( $limit ) == 'all') {
			return $model->where($where)->count ();
		}
		$res = $model->where($where)->order ( $order )->limit ( $limit )->select();
		return $res;
	 }
	/**
	 * 获取云购平台信息
	 * @param int     $id 云购平台信息ID
	 * @param int     $userid 用户ID
	 * @return array
	 * */
	 function get_biz_detail($id,$userid=0){
		$this->dao = M('UserBiz');
		if($userid != 0){
			return $this->select_ext('',array('user_id'=>$userid),'*',false);
		}
		return $this->select($id);
	 }
	 /**
	 * 云购商家平台信息操作日志列表
	 * @param array     $_arr=array(
	 * 					'userid'=>用户ID
	 * 					)
	 * @return array
	 * */
	 function biz_log_list($_arr=array(),$limit = '0,20',$order = 'id DESC',$isall = true){
		$model = M('UserBizLog');
		$where = array();
		if($_arr != 'all'){
			foreach ($_arr as $key => $value) {
				$where[$key] = $value;
			}
		}
		if($isall !== false){
			if (strtolower ( $limit ) == 'all') {
				return $model->where($where)->count ();
			}
			$rel = $model->where($where)->order ( $order )->limit ( $limit )->select();
			return $rel;
		}else{
			$rel = $model->where($where)->order ( $order )->select();
			return $rel;
		}
	 }
	 /**
	  * 查询用户权限
	  * @param int	 	$userid	用户ID
	  * @return array
	  * */
	 function get_role($userid){
	 	return $this->select_ext(M('RoleUser'),array('user_id' => $userid),"role_id");
	 }
	 /**
	  * 添加用户
	  * @param array    $info			要添加的数据
	  * @param array 	$field_exist	设置不可重复的字段
	  * @param array 	$field_null		设置不可为空的字段
	  * @param int	 	$userid			帐户ID
	  * @param int	 	$action_userid	操作人编号
	  * @param varchar 	$remark			操作特殊备注
	  * @return array 	成功返回 {"status":"1","msg":"信息","data":data,"id":序列号} 失败返回 {"status":"0","msg":"信息","data":data}
	  * */
	function biz_add($info=array(),$field_exist=array(),$field_null=array(),$userid=0,$action_userid=0,$remark=null){
		$this->dao = M('UserBiz');
		unset($this->post);
		foreach ($field_null as $key => $value) {
			if(empty($info[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $info[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post = $info;
		$resid = $this->insert();
		if(false !== $resid){
			$log['userid'] = $userid;
			$log['type'] = 1;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('id'=>$resid);
			return $this->_suc($res,'注册成功');
		}else{
			return $this->_err("添加失败请重试");
		}
	}
	/**
	 * 修改用户
	 * @param array    	$info			要更新的数据
	 * @param array 	$field_exist	设置不可重复的字段
	 * @param array 	$field_null		设置不可为空的字段
	 * @param int	 	$userid			帐户ID
	 * @param int	 	$action_userid	操作人编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function biz_edit($info=array(),$field_exist=array(),$field_null=array(),$userid=0,$action_userid=0,$remark=null){
		$this->dao = M('UserBiz');
		unset($this->post);
		$this->userid = $info['id'];
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
		foreach ($field_null as $key => $value) {
			if(empty($info[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $info[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post['id'] = $this->userid;
		$this->post = $info;
		$status = $this->update();
		if(false !== $status){
			$log['userid'] = $userid;
			$log['type'] = 5;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 付款状态
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function biz_pay_status($id,$userid=0,$action_userid=0,$status=0,$remark=null){
		$this->dao = M('UserBiz');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['pay_status'] = $status;
		$status = $this->update();
		if(false !== $status){
			$log['userid'] = $userid;
			$log['type'] = 2;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'设置支付状态成功');
		}else{
			return $this->_err("设置支付状态失败请重试");
		}
	}
	/**
	 * 审核用户
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function biz_status($id,$userid=0,$action_userid=0,$status=0,$remark=null){
		$this->dao = M('UserBiz');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['status'] = $status;
		$ret = $this->update();
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 3;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$ret);
			return $this->_suc($res,'设置审核状态成功');
		}else{
			return $this->_err("设置审核状态失败请重试");
		}
	}
	/**
	 * 开通状态
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param int		$roleid			权限编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function biz_isclose($id,$userid=0,$action_userid=0,$status=0,$roleid=15,$remark=null){
		$this->dao = M('UserBiz');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['isclose'] = $status;
		$ret = $this->update();
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 4;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			if($status==2){
				$this->set_role_status($roleid,1,$userid);
			}else{
				$this->set_role_status($roleid,0,$userid);
			}
			
			$res=array('mStatus'=>$ret);
			return $this->_suc($res,'设置开通状态成功');
		}else{
			return $this->_err("设置开通状态失败请重试");
		}
	}
	public function set_role_status($roleid,$status,$userid){
		if(!empty($this->platform)){
			if(!empty($roleid)){
				$ret = $this->select_ext(M('RoleUser'),array('role_id'=>$roleid,'user_id'=>$userid),'id',false);
				if(empty($ret)){
					$role['role_id'] = $roleid;
					$role['user_id'] = $userid;
					$role['ctime'] = time();
					$this->insert_ext(M('RoleUser'),$role);
				}
			}
			$ret = $this->select_ext(M('UserExt'),array('userid'=>$userid,'element'=>'status','platform'=>$this->platform),'id,value',false);
			if(empty($ret)){
				$ext['value'] = $status;
				$ext['userid'] = $userid;
				$ext['element'] = "status";
				$ext['title'] = "状态";
				$ext['platform'] = $this->platform;
				$this->insert_ext(M('UserExt'),$ext);
			}else{
				if($ret['value']!=$status){
					$this->update_ext(M('UserExt'),array('value'=>$status),$ret['id']);
				}
			}
		}
	}
	/**
	 * 校验用户名是否合法
	 * */
	private function _check($fn,$val){
		$model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
	}
	/**
     * 查询某个字段是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回false，不存在返回true
     */
    private function field_exist($fn,$val){
        $model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
		//$this->debug = $model->getlastsql();
        if($rel === false || empty($rel) || $rel['id'] == $this->userid){
            return true;
        }else{
            return false;
        }
    }
    /**
	 *请求接口类型异常
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _err($str="暂无相关信息") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			return $this->myjson($res);
		}
		
	}//end _err
	
	/**
	 *请求成功返回
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _suc($arr=array(),$str="操作成功") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			return $this->myjson($res);
		}
		
	}//end _suc
	/**
	 * 对url或其它字符转义
	 * */
	private function myjson($code) {
		$code = json_encode ( $this->urlencodeAry ( $code ) );
		return urldecode ( $code );
		//return $code;
	}
	private function urlencodeAry($data) {
		if (is_array ( $data )) {
			foreach ( $data as $key => $val ) {
				$data [$key] = $this->urlencodeAry ( $val );
			}
			return $data;
		} else {
			return urlencode ( $data );
		}
	}
	
	/**
	 * 操作插入数据表
	 * */
	private function insert(){
		$model = $this->dao;
		$_POST = $this->post;
		if (false === $model->create ()) {
			return false;
		}
		$result = $model->add ();
		if ($result !== false) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作更新数据表
	 * */
	private function update(){
		$model = $this->dao;
		if (false === $model->create ($this->post)) {
			return false;
		}
		$result = $model->save ();
		$this->debug = $model->getlastsql();
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作删除数据表
	 * */
	private function delete(){
		$model = $this->dao;
		$result = $model->delete ($this->userid);
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作查询数据表
	 * @param $id 查询用户ID
	 * @return 如果存在返回用户信息，不存在返回false，参数$id空返回所有用户信息
	 * */
	private function select($id){
		$model = $this->dao;
		if(!empty($id)){
			$result = $model->find ($id);
			return $result;
		}else{
			$result = $model->select ();
			return $result;
		}
	}
	/**
	 * 操作添加用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function insert_ext($table_ext,$field_value = array()){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		$this->post = $field_value;
		$rel = $this->insert();
		return $rel;
	}
	/**
	 * 操作更新用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function update_ext($table_ext,$field_value = array(),$id){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		if(!empty($id)){
			$field_value['id'] = $id;
			$this->post = $field_value;
		}
		$rel = $this->update();
		return $rel;
	}
	/**
	 * 操作删除用户关联扩展或附属数据表
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function delete_ext($id){
		if(!empty($id)){
			$this->userid = $id;
		}
		$rel = $this->delete();
	}
	/**
	 * 操作查询用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回查询信息，不存在返回false
	 * */
	private function select_ext($table_ext,$field_value = array(),$field = "*",$isall = true){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		$rel = $this->select_all($field_value,$field,$isall);
		return $rel;
	}
	/**
     * 自定义查询条件查询数据
	 * @param array $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回所有信息，不存在返回false
     */   
    private function select_all($field_value = array(),$field = "*",$isall = true){
        $model = $this->dao;
		$where = "";
		foreach ($field_value as $key => $value) {
			if(empty($where)){
				$where = $key."='".$value."'";
			}else{
				$where .= " AND ".$key."='".$value."'";
			}
		}
		$rel = array();
		if($isall == true){
			$rel = $model->field($field)->where($where)->select();
			//$this->debug = $model->getlastsql();
		}else{
			$rel = $model->field($field)->where($where)->find();
			//$this->debug = $model->getlastsql();
		}
        if(!empty($rel)){//$rel !== false ||
            return $rel;
        }else{
            return false;
        }
    }
	/**
     * 查询用户是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回一条用户信息，不存在返回false
     */
    private function select_field($fn,$val){
        $model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
    }
}